import xlrd, verify,pva, MuTestApi, sys, getopt

USERNAME = 'admin'
PASSWORD = ''
MU = ''
WORKBOOK = ''
OUTPUT = ''
HEADERS = []
RESULTS = []
VERBOSE = False

def usage():
	print '------------------- USAGE --------------------'
	print "python runExcelTest.py -i https://demo.myMu.dom -u admin -p myPassword -w /path/myWorkbook.xls -o /path/myOutput.csv"
	print "-i = url or ipadress of the Mu plaftorm"
	print "-u = username, only admin can run API"
	print "-p = password for admin"
	print "-w = full path and name for USGv6 workbook"
	print "-o = full path and name for output csv file"
	print "-v for increased verbosity"
	sys.exit(2)

def writeResults(output):
	data = ""
	newFile = open(output, "wt")
	for result in RESULTS:
		testType = result[1]
		worksheetName = result[0]
		if testType=='PVA':
			results = result[3]
			testName = result[2]
			if results[0]=="ERROR":
				data = '"'+worksheetName+'","'+testType+'","'+testName+'","'+results[0]+'","'+results[1]+'"'
			else:
				data = '"'+worksheetName+'","'+testType+'","'+testName+'","'+results[0]+'","'+results[1]+'","'+str(results[2])+'","'+str(results[3])+'"'
			#print "----->" + data + "<-----"
			newFile.write(data)
		elif testType=='VERIFY':
			results = result[2]
			for singleResult in results:
				if not singleResult.testResult=="END":
					data = '"'+worksheetName+'","'+testType+'",'+singleResult.getAsCsv()
					newFile.write(data)
	newFile.close()
		

#get the username and password
args = sys.argv[0:]
try:
    options, remainder = getopt.getopt(sys.argv[1:], "u:p:i:w:o:v", ["username=", "password=","ipaddress=", "workbook=", "output=","verbose"])
except getopt.GetoptError, err:
    # print help information and exit:
    print str(err) # will print something like "option -a not recognized"
    usage()
    sys.exit(2)
for o, p in options:
    if o in ("-u","--username"):
		USERNAME = p
    elif o in ("-p", "--password"):
		PASSWORD = p
    elif o in ("-i", "--ipaddress"):
		MU = p
    elif o in ("-w", "--workbook"):
		WORKBOOK = p
    elif o in ("-o", "--output"):
    	OUTPUT = p
    elif o in ("-v", "--verbose"):
    	VERBOSE = True
    else:
    	usage()

if MU=='':
	usage()
if PASSWORD=='':
	usage()
if WORKBOOK=='':
	usage()
if OUTPUT=='':
	usage()

book = xlrd.open_workbook(WORKBOOK)
	
# lets find the test sheet and set up the test
testConfigData = book.sheet_by_name("TestAutomationConfig")

for rx in range(testConfigData.nrows):
	row = testConfigData.row(rx)
	if row[0] == None or row[0] == '':
		print "empty row"
	elif row[0].value == "VERIFY":
		scenarioName = row[1].value
		uuid = row[2].value
		testWorksheetName = row[3].value
		host_0 = row[4].value
		host_1 = row[5].value
		host_2 = row[6].value
		host_3 = row[7].value
		csvName = testWorksheetName
		csvData = None
		csvUUID = None
		if testWorksheetName.startswith("UUID") or testWorksheetName.startswith("uuid"):
			csvUUID = testWorksheetName.split("=")[1]
			print "-----------------" + testWorksheetName + "-------------------------"
			# need to add trim whitespace is spaces are present
			#print csvUUID
		else:
			csvUUID = None
			testCaseWorksheet = book.sheet_by_name(testWorksheetName)
			print "-----------------" + testWorksheetName + "-------------------------"
			for rx2 in range(testCaseWorksheet.nrows):
				row2 = testCaseWorksheet.row(rx2)
				for cell in row2:
					if csvData==None:
						csvData = '"'+str(cell.value)+'"'
					elif csvData.endswith("\n"):
						csvData = csvData + '"'+str(cell.value)+'"'
					else:
						csvData = csvData + "," + '"'+str(cell.value)+'"'
				csvData = csvData + "\n"
			#csvData = csvData + "\n"
			#print csvData
		try:
			myVerifyTest = verify.verify(MU,USERNAME,PASSWORD,uuid,csvUUID,csvData,csvName,[host_0,host_1,host_2,host_3],False,VERBOSE)
			#myVerifyTest.resultsToCsvFile(OUTPUT)
			RESULTS.append([testWorksheetName,'VERIFY',myVerifyTest.results])
			headers =  myVerifyTest.getResultHeaders().split(',')
			if len(headers)>len(HEADERS):
				HEADERS = headers
		except:
			print "ERROR: VERIFY TEST FAILED TO COMPLETE: " + testWorksheetName
			result = MuTestApi.Result(None)
			result.status = 'ERROR: VERIFY TEST FAILED TO COMPLETE'
			result.testName = csvName
			result.testResult = 'ERROR'
			RESULTS.append([testWorksheetName,'VERIFY',[result]])
	elif row[0].value == "PVA":		
		scenarioName = row[1].value
		uuid = row[2].value
		testWorksheetName = row[3].value
		host_0 = row[4].value
		host_1 = row[5].value
		host_2 = row[6].value
		host_3 = row[7].value
		print "-----------------" + testWorksheetName + "-------------------------"
		#print scenarioName+", "+uuid+", "+testWorksheetName+", "+host_0+", "+host_1+", "+host_2+", "+host_3
		testCaseWorksheet = book.sheet_by_name(testWorksheetName)
		name = testCaseWorksheet.cell(0,1).value
		blockFailMax = testCaseWorksheet.cell(2,1).value
		faultMax = testCaseWorksheet.cell(3,1).value
		myPvaTest = pva.pva(MU,USERNAME,PASSWORD,uuid,host_0,host_1,name,blockFailMax,faultMax,VERBOSE)
		RESULTS.append([testWorksheetName,'PVA',name,myPvaTest.summary])
	elif row[0] == "DOS":
		print "TODO: DOS"
	elif row[0] == "PROTOCOL":
		print "TODO: PROTOCOL"
	elif row[0] == "SCALE":
		print "TODO: SCALE"
	elif row[0] == "FUZZ":
		print "TODO: FUZZ"
	else:
		print "UNKNOWN TEST TYPE: " + str(row[0])

writeResults(OUTPUT)
	